package com.zsk.shop.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.base.page.BasePageFactory;
import com.zsk.shop.common.constant.RedisKeys;
import com.zsk.shop.common.utils.*;
import com.zsk.shop.entity.*;
import com.zsk.shop.enums.EnumDataDictionaryKey;
import com.zsk.shop.enums.EnumGoodsPublishType;
import com.zsk.shop.enums.EnumGoodsType;
import com.zsk.shop.enums.ServiceKeyTypeEnum;
import com.zsk.shop.mapper.ShopGoodsMapper;
import com.zsk.shop.model.params.*;
import com.zsk.shop.model.results.GoodsTypeResult;
import com.zsk.shop.model.results.HomeGoodsResult;
import com.zsk.shop.model.results.ShopGoodsDetailResult;
import com.zsk.shop.model.results.ShopGoodsInfoResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ljh
 * @create 2021/11/17 16:12
 */
@Service
@DS("miniShop")
public class ShopGoodsService extends ServiceImpl<ShopGoodsMapper, ShopGoods> {

    private static final Logger logger = LoggerFactory.getLogger(ShopGoodsService.class);

    @Resource
    private ShopGoodsSkuService shopGoodsSkuService;
    @Resource
    private ShopOrderService shopOrderService;
    @Resource
    private ShopGoodsCategoryService shopGoodsCategoryService;
    @Resource
    private ShopGoodsLabelService shopGoodsLabelService;
    @Resource
    private ShopCollectionService shopCollectionService;
    @Resource
    private ShopUserService shopUserService;

    public BaseResponse<List<ShopGoodsInfoResult>> getGoodsList(ShopGoodsInfoParam param) {
        Page pageContext = BasePageFactory.defaultPage(param.getPage(), param.getLimit());
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        if (ToolUtil.isNotEmpty(param.getGoodsName())) {
            queryWrapper.like(ShopGoods::getGoodsName, param.getGoodsName());
        }
        if (ToolUtil.isNotEmpty(param.getStatus())) {
            if (param.getStatus().equals("true")) {
                queryWrapper.eq(ShopGoods::getStatus, true);
            }
            if (param.getStatus().equals("false")) {
                queryWrapper.eq(ShopGoods::getStatus, false);
            }
        }
        if (ToolUtil.isNotEmpty(param.getGoodsOrderType())) {
            //商品类型
            List<Integer> goodsTypes = EnumGoodsType.getGoodsTypeByGoodsOrderType(Integer.parseInt(param.getGoodsOrderType()));
            queryWrapper.in(ShopGoods::getGoodsType, goodsTypes);
        }
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        queryWrapper.orderByDesc(ShopGoods::getStatus, ShopGoods::getUpdateTime);
        IPage page = this.page(pageContext, queryWrapper);
        List<ShopGoods> shopGoodsList = page.getRecords();
        List<ShopGoodsInfoResult> result = EntityConvertUtils.convertAListToBList(shopGoodsList, ShopGoodsInfoResult.class);
        List<String> goodsNos = result.stream().map(ShopGoodsInfoResult::getGoodsNo).collect(Collectors.toList());
        if (ToolUtil.isEmpty(goodsNos)) {
            return BasePageFactory.createPageInfo(page);
        }
        //所有商品SKU集合
        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNos(goodsNos);
        //所有分类集合
        List<ShopGoodsCategory> shopGoodsCategoryList = shopGoodsCategoryService.queryLevelOne();
        List<ShopGoodsLabel> shopGoodsLabelList = shopGoodsLabelService.labelList();
        for (ShopGoodsInfoResult homeShopGoodsResult : result) {
            //主图处理
            String images = homeShopGoodsResult.getGoodsImgs();
            if (images.indexOf(",") != -1) {
                homeShopGoodsResult.setGoodsImgs(images.substring(0, images.indexOf(",")));
            }
            homeShopGoodsResult.setGoodsTypeResult(EnumGoodsType.getGoodsTypeByType(homeShopGoodsResult.getGoodsType()));
            String goodsNo = homeShopGoodsResult.getGoodsNo();
            List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuList.stream().filter(x -> x.getGoodsNo().equals(goodsNo)).collect(Collectors.toList());
            //sku所有虚销售量
            Integer skuSaleVolume = 0;
            //订单所有销售量
            Integer salesVolume = shopOrderService.countByGoodsNo(goodsNo);
            homeShopGoodsResult.setSaleCount(skuSaleVolume + salesVolume);
            //sku所有库存
            Integer allStock = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getStock).sum();
            homeShopGoodsResult.setAllStock(allStock);
            //查询单买价格
            ShopGoodsSku shopGoodsSkuLowPrice = shopGoodsSkus.stream().sorted(Comparator.comparing(ShopGoodsSku::getPrice)).collect(Collectors.toList()).get(0);
            homeShopGoodsResult.setPrice(shopGoodsSkuLowPrice.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            ShopGoodsCategory shopGoodsCategory = shopGoodsCategoryList.stream().filter(s -> s.getCategoryNo().equals(homeShopGoodsResult.getGoodsCategoryNo()))
                    .findFirst().orElse(new ShopGoodsCategory());
            ShopGoodsLabel shopGoodsLabel = shopGoodsLabelList.stream().filter(s -> s.getLabelNo().equals(homeShopGoodsResult.getGoodsLabelNo()))
                    .findFirst().orElse(new ShopGoodsLabel());
            homeShopGoodsResult.setGoodsCategoryName(shopGoodsCategory.getCategoryName());
            homeShopGoodsResult.setGoodsLabelName(shopGoodsLabel.getLabelName());
            homeShopGoodsResult.setPreSaleTime(homeShopGoodsResult.getHavePreSaleTime() ? homeShopGoodsResult.getPreSaleTime() : null);
        }
        page.setRecords(result);
        return BasePageFactory.createPageInfo(page);
    }

    /**
     * 添加/编辑 商品
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse addOrEditGoods(AddShopGoodsParams params) {
        ShopGoods shopGoods = EntityConvertUtils.convertAToB(params, ShopGoods.class);
        List<AddShopGoodsSkuParams> skuParamsList = params.getSkuList();
        List<ShopGoodsSku> shopGoodsSkus = EntityConvertUtils.convertAListToBList(skuParamsList, ShopGoodsSku.class);
        String operatorUserNo = ToolUtil.isEmpty(HttpContext.getSafeUserNo()) ? "" : HttpContext.getSafeUserNo();
        Date time = new Date();
        if (skuParamsList.size() < 1) {
            return BaseResponse.error("未设置SKU操作失败。");
        }
        if (params.getIsAdd()) {
            String goodsNo = RedisUtil.getServiceKeyHaveDateByType(ServiceKeyTypeEnum.GOODS.getValue());
            shopGoods.setGoodsNo(goodsNo);
            shopGoods.setAccordingLabelShow(false);
            GoodsTypeResult goodsTypeResult = GoodsTypeResult.builder().isVipBuyGoods(params.getIsVipBuyGoods())
                    .isAgainGoods(params.getIsAgainGoods())
                    .isGoods(params.getIsGoods()).isVipGoods(params.getIsVipGoods()).isZoneGoods(params.getIsZoneGoods()).build();
            Integer goodsType = EnumGoodsType.genType(goodsTypeResult);
            shopGoods.setGoodsType(goodsType);
            if (goodsType.equals(EnumGoodsType.AGAIN.getType()) && ToolUtil.isNotEmpty(params.getAgainVipLevel())) {
                shopGoods.setAgainVipLevel(params.getAgainVipLevel());
            }
            if (params.getPublishType().equals(EnumGoodsPublishType.NOT.getType())) {
                shopGoods.setStatus(false);
            } else {
                if (ToolUtil.isNotEmpty(params.getPublishTime())) {
                    if (time.getTime() <= DateUtils.parse2Date(params.getPublishTime(), DateUtils.YYYYMMDDHHMMSS).getTime()) {
                        shopGoods.setStatus(false);
                    } else {
                        shopGoods.setStatus(true);
                    }
                } else {
                    shopGoods.setPublishTime(time);
                    shopGoods.setStatus(true);
                }
            }
            for (ShopGoodsSku shopGoodsSku : shopGoodsSkus) {
                shopGoodsSku.setBizNo(RedisUtil.getServiceKeyHaveDateByType(ServiceKeyTypeEnum.GOODS_SKU.getValue()));
                shopGoodsSku.setGoodsNo(goodsNo);
                shopGoodsSku.setScribingPrice(ToolUtil.isNotEmpty(shopGoodsSku.getScribingPrice()) ? shopGoodsSku.getScribingPrice() : shopGoodsSku.getPrice());
                if (goodsType.equals(EnumGoodsType.AGAIN.getType())) {
                    shopGoodsSku.setPrice(shopGoodsSku.getAgainPrice());
                    shopGoodsSku.setSpecialPrice(shopGoodsSku.getAgainPrice());
                    shopGoodsSku.setScribingPrice(shopGoodsSku.getAgainPrice());
                    shopGoodsSku.setVipPrice(shopGoodsSku.getAgainPrice());
                }
            }
            shopGoodsSkuService.saveOrUpdateBatch(shopGoodsSkus);
            shopGoods.setCreateUser(operatorUserNo);
            shopGoods.setCreateTime(time);
            if (ToolUtil.isNotEmpty(params.getPreSaleTime())) {
                shopGoods.setHavePreSaleTime(true);
                shopGoods.setPreSaleTime(DateUtils.parse2Date(params.getPreSaleTime(), DateUtils.YYYYMMDDHHMMSS));
            } else {
                shopGoods.setHavePreSaleTime(false);
            }
        } else {
            String goodsNo = params.getGoodsNo();
            shopGoods = this.queryByGoodsNo(goodsNo);
            //修改主要填写信息
            if (ToolUtil.isNotEmpty(params.getGoodsName())) {
                shopGoods.setGoodsName(params.getGoodsName());
            }
            if (ToolUtil.isNotEmpty(params.getIntroduction())) {
                shopGoods.setIntroduction(params.getIntroduction());
            }
            if (ToolUtil.isNotEmpty(params.getGoodsCategoryNo())) {
                shopGoods.setGoodsCategoryNo(params.getGoodsCategoryNo());
            } else {
                shopGoods.setGoodsCategoryNo("");
            }
            if (ToolUtil.isNotEmpty(params.getGoodsLabelNo())) {
                shopGoods.setGoodsLabelNo(params.getGoodsLabelNo());
            } else {
                shopGoods.setGoodsLabelNo("");
            }
            if (ToolUtil.isNotEmpty(params.getGoodsImgs())) {
                shopGoods.setGoodsImgs(params.getGoodsImgs());
            }
            if (ToolUtil.isNotEmpty(params.getGoodsDetail())) {
                shopGoods.setGoodsDetail(params.getGoodsDetail());
            }
            if (ToolUtil.isNotEmpty(params.getLimitBuyCount())) {
                shopGoods.setLimitBuyCount(params.getLimitBuyCount());
            }
            Integer goodsType = EnumGoodsType.EIGHT.getType();
            if (!ToolUtil.isAllEmpty(params.getIsVipBuyGoods(), params.getIsVipGoods(), params.getIsGoods()
                    , params.getIsVipGoods(), params.getIsZoneGoods())) {
                GoodsTypeResult goodsTypeResult = GoodsTypeResult.builder().isVipBuyGoods(params.getIsVipBuyGoods())
                        .isAgainGoods(params.getIsAgainGoods())
                        .isGoods(params.getIsGoods()).isVipGoods(params.getIsVipGoods()).isZoneGoods(params.getIsZoneGoods()).build();
                goodsType = EnumGoodsType.genType(goodsTypeResult);
                shopGoods.setGoodsType(goodsType);
                if (goodsType.equals(EnumGoodsType.ZERO.getType()) && ToolUtil.isNotEmpty(params.getVipLevel())) {
                    shopGoods.setVipLevel(params.getVipLevel());
                }
                if (goodsType.equals(EnumGoodsType.AGAIN.getType()) && ToolUtil.isNotEmpty(params.getAgainVipLevel())) {
                    shopGoods.setAgainVipLevel(params.getAgainVipLevel());
                }
            }
            if (ToolUtil.isNotEmpty(params.getPreSaleTime())) {
                shopGoods.setHavePreSaleTime(true);
                shopGoods.setPreSaleTime(DateUtils.parse2Date(params.getPreSaleTime(), DateUtils.YYYYMMDDHHMMSS));
            } else {
                shopGoods.setHavePreSaleTime(false);
            }
            //修改SKU
            List<ShopGoodsSku> shopGoodsSkusHave = shopGoodsSkuService.listByGoodsNo(goodsNo);
            //根据传过来的sku-id找到原来的sku,如果1>原来存在的id现在没有传了就删除，2>sku不带id的新增，3>原来存在的id现在也有就修改
            List<ShopGoodsSku> shopGoodsSkusAdd = shopGoodsSkus.stream().filter(x -> ToolUtil.isEmpty(x.getId())).collect(Collectors.toList());
            List<Long> shopGoodsSkusHaveId = shopGoodsSkus.stream().filter(x -> ToolUtil.isNotEmpty(x.getId())).map(ShopGoodsSku::getId).collect(Collectors.toList());
            List<ShopGoodsSku> shopGoodsSkusEdit = shopGoodsSkus.stream().filter(x -> ToolUtil.isNotEmpty(x.getId()) && shopGoodsSkusHaveId.contains(x.getId())).collect(Collectors.toList());
            List<ShopGoodsSku> shopGoodsSkusDeleted = shopGoodsSkusHave.stream().filter(x -> !shopGoodsSkusHaveId.contains(x.getId())).collect(Collectors.toList());
            //add
            if (ToolUtil.isNotEmpty(shopGoodsSkusAdd)) {
                for (ShopGoodsSku skuAdd : shopGoodsSkusAdd) {
                    skuAdd.setBizNo(RedisUtil.getServiceKeyHaveDateByType(ServiceKeyTypeEnum.GOODS_SKU.getValue()));
                    skuAdd.setGoodsNo(goodsNo);
                    skuAdd.setScribingPrice(skuAdd.getPrice());
                    if (goodsType.equals(EnumGoodsType.AGAIN.getType())) {
                        skuAdd.setPrice(skuAdd.getAgainPrice());
                        skuAdd.setSpecialPrice(skuAdd.getAgainPrice());
                        skuAdd.setScribingPrice(skuAdd.getAgainPrice());
                        skuAdd.setVipPrice(skuAdd.getAgainPrice());
                    }
                }
                shopGoodsSkuService.saveOrUpdateBatch(shopGoodsSkusAdd);
            }
            if (ToolUtil.isNotEmpty(shopGoodsSkusDeleted)) {
                //deleted
                for (ShopGoodsSku skuDeleted : shopGoodsSkusDeleted) {
                    skuDeleted.setIsDeleted(true);
                }
                shopGoodsSkuService.saveOrUpdateBatch(shopGoodsSkusDeleted);
            }
            if (ToolUtil.isNotEmpty(shopGoodsSkusEdit)) {
                //edit
                shopGoodsSkuService.saveOrUpdateBatch(shopGoodsSkusEdit);
            }
            logger.info(JSON.toJSONString(shopGoodsSkusEdit));
            //修改其他 发布时间相关内容
            if (params.getPublishType().equals(EnumGoodsPublishType.NOT.getType())) {
                shopGoods.setStatus(false);
            } else {
                if (ToolUtil.isNotEmpty(params.getPublishTime())) {
                    if (time.getTime() <= DateUtils.parse2Date(params.getPublishTime(), DateUtils.YYYYMMDDHHMMSS).getTime()) {
                        shopGoods.setStatus(false);
                    } else {
                        shopGoods.setStatus(true);
                    }
                } else {
                    shopGoods.setPublishTime(time);
                    shopGoods.setStatus(true);
                }
            }
        }
        shopGoods.setUpdateUser(operatorUserNo);
        shopGoods.setUpdateTime(time);
        this.saveOrUpdate(shopGoods);
        return BaseResponse.success("添加/修改商品成功");
    }

    /**
     * GOP商品详情
     *
     * @param goodsNo
     * @return
     */
    public BaseResponse<AddShopGoodsParams> gopGoodsDetailByNo(String goodsNo) {
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsNo, goodsNo);
        queryWrapper.last("limit 1");
        ShopGoods shopGoods = this.getOne(queryWrapper);
        AddShopGoodsParams result = EntityConvertUtils.convertAToB(shopGoods, AddShopGoodsParams.class);
        ShopGoodsCategory shopGoodsCategory = shopGoodsCategoryService.queryByCategoryNo(result.getGoodsCategoryNo());
        result.setGoodsCategoryName(ToolUtil.isNotEmpty(shopGoodsCategory) ? shopGoodsCategory.getCategoryName() : "");
        ShopGoodsLabel shopGoodsLabel = shopGoodsLabelService.queryByLabelNo(result.getGoodsLabelNo());
        result.setGoodsLabelName(ToolUtil.isNotEmpty(shopGoodsLabel) ? shopGoodsLabel.getLabelName() : "");
        GoodsTypeResult goodsTypeResult = EnumGoodsType.getGoodsTypeByType(result.getGoodsType());
        result.setIsVipBuyGoods(goodsTypeResult.getIsVipBuyGoods());
        result.setIsGoods(goodsTypeResult.getIsGoods());
        result.setIsVipGoods(goodsTypeResult.getIsVipGoods());
        result.setIsZoneGoods(goodsTypeResult.getIsZoneGoods());
        result.setIsAgainGoods(goodsTypeResult.getIsAgainGoods());
        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNo(goodsNo);
        List<AddShopGoodsSkuParams> skuParamsList = EntityConvertUtils.convertAListToBList(shopGoodsSkuList, AddShopGoodsSkuParams.class);
        result.setSkuList(skuParamsList);
        //返回预售标志
        result.setPreSaleTime(result.getHavePreSaleTime() ? result.getPreSaleTime() : "");
        return BaseResponse.success(result);
    }

    public BaseResponse reviewGoods(Long id, Boolean letDisable) {
        LambdaUpdateWrapper<ShopGoods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ShopGoods::getStatus, !letDisable);
        updateWrapper.eq(ShopGoods::getId, id);
        if (letDisable) {
            updateWrapper.set(ShopGoods::getPublishTime, null);
        }
        this.update(updateWrapper);
        return BaseResponse.success("商品上下架成功");
    }

    /**
     * 商品详情
     *
     * @param goodsNo
     * @return
     */
    public BaseResponse<ShopGoodsDetailResult> goodsDetailByNo(String goodsNo, Integer goodsOrderType) {
        if (ToolUtil.isEmpty(goodsOrderType)) {
            goodsOrderType = 1;
        }
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsNo, goodsNo);
        queryWrapper.last("limit 1");
        ShopGoods shopGoods = this.getOne(queryWrapper);
        ShopGoodsDetailResult result = EntityConvertUtils.convertAToB(shopGoods, ShopGoodsDetailResult.class);
        ShopUser shopUser = shopUserService.queryByUserNo(HttpContext.getSafeUserNo());
        if (ToolUtil.isNotEmpty(shopUser) && ToolUtil.isNotEmpty(shopUser.getVipLevel())) {
            result.setIsVip(shopUser.getVipLevel() > 0 ? true : false);
        }
        if (ToolUtil.isNotEmpty(shopUser) && ToolUtil.isNotEmpty(shopUser.getParentUserNo())) {
            result.setIsShow(false);
        }
        result.setIsPreSale(false);
        if (shopGoods.getHavePreSaleTime()) {
            if (ToolUtil.isNotEmpty(shopGoods.getPreSaleTime())) {
                Date time = new Date();
                if (time.getTime() <= shopGoods.getPreSaleTime().getTime()) {
                    result.setIsPreSale(true);
                }
            }
        }
        result.setCanBuyZeroGoods(false);
        GoodsTypeResult goodsTypeResult = EnumGoodsType.getGoodsTypeByType(result.getGoodsType());
        result.setIsVipBuyGoods(goodsTypeResult.getIsVipBuyGoods());
        result.setIsGoods(goodsTypeResult.getIsGoods());
        result.setIsVipGoods(goodsTypeResult.getIsVipGoods());
        result.setIsZoneGoods(goodsTypeResult.getIsZoneGoods());
        result.setIsCollection(shopCollectionService.isCollection(HttpContext.getSafeUserNo(), shopGoods.getGoodsNo(), goodsOrderType));
        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNo(goodsNo);
        result.setSkuList(shopGoodsSkuList);
        // 验证入口来源 返回对应价格
        ShopGoodsSku shopGoodsSkuLowPrice = shopGoodsSkuList.stream().sorted(Comparator.comparing(ShopGoodsSku::getPrice)).collect(Collectors.toList()).get(0);
        ShopGoodsSku shopGoodsSkuLowAgainPrice = shopGoodsSkuList.stream().sorted(Comparator.comparing(ShopGoodsSku::getAgainPrice)).collect(Collectors.toList()).get(0);
        if (goodsOrderType.equals(1)) {
            result.setPrice(shopGoodsSkuLowPrice.getPrice().toString());
        } else if (goodsOrderType.equals(2)) {
            result.setPrice(shopGoodsSkuLowPrice.getPrice().toString());
            result.setZeroPrice("0.00");
            result.setPostage(RedisUtil.get(RedisKeys.dictionaryKey(EnumDataDictionaryKey.POSTAGE.getKey())).toString());
        } else if (goodsOrderType.equals(3)) {
            ShopGoodsSku shopGoodsSkuLowVipPrice = shopGoodsSkuList.stream().sorted(Comparator.comparing(ShopGoodsSku::getVipPrice)).collect(Collectors.toList()).get(0);
            result.setPrice(shopGoodsSkuLowVipPrice.getPrice().toString());
            result.setVipPrice(shopGoodsSkuLowVipPrice.getVipPrice().toString());
        } else if (goodsOrderType.equals(4)) {
            result.setPrice(shopGoodsSkuLowPrice.getPrice().toString());
            result.setReturnPoints(shopGoodsSkuLowPrice.getReturnPoints());
        } else if (goodsOrderType.equals(5)) {
            result.setPrice(shopGoodsSkuLowPrice.getPrice().toString());
            result.setAgainPrice(shopGoodsSkuLowAgainPrice.getAgainPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            result.setReturnPoints(shopGoodsSkuLowPrice.getReturnPoints());
        }
        if (ToolUtil.isNotEmpty(shopGoodsSkuLowPrice.getSpecialPrice())) {
            result.setSpecialPrice(shopGoodsSkuLowPrice.getSpecialPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        } else {
            result.setSpecialPrice(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        if (!shopGoods.getStatus()) {
            for (ShopGoodsSku shopGoodsSku : shopGoodsSkuList) {
                shopGoodsSku.setStock(0);
            }
            result.setSkuList(shopGoodsSkuList);
        }
        for (ShopGoodsSku shopGoodsSku : shopGoodsSkuList) {
            if (goodsOrderType.equals(1)) {
                shopGoodsSku.setReturnPoints(0);
            }
        }
        //sku所有虚销售量
        Integer skuSaleVolume = shopGoodsSkuList.stream().mapToInt(ShopGoodsSku::getSalesVolume).sum();
        //订单所有销售量
        Integer salesVolume = shopOrderService.countByGoodsNo(goodsNo);
        result.setSaleCount(skuSaleVolume + salesVolume);
        return BaseResponse.success(result);
    }

    /**
     * 分类下的商品
     *
     * @return
     */
    public BaseResponse<List<HomeGoodsResult>> getCategoryFirstGoodsList(CategoryGoodsParams params) {
        Page pageContext = BasePageFactory.defaultPage(params.getPage(), params.getLimit());
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsCategoryNo, params.getGoodsCategoryNo());
        queryWrapper.eq(ShopGoods::getStatus, true);
        queryWrapper.and(x -> x.eq(ShopGoods::getPublishType, 1).or().eq(ShopGoods::getPublishType, 2)
                .and(y -> y.isNull(ShopGoods::getPublishTime).or().le(ShopGoods::getPublishTime, new Date())));
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        queryWrapper.ne(ShopGoods::getGoodsType, -1);
        queryWrapper.orderByDesc(ShopGoods::getUpdateTime);
        IPage page = this.page(pageContext, queryWrapper);
        List<ShopGoods> shopGoodsList = page.getRecords();
        List<HomeGoodsResult> result = EntityConvertUtils.convertAListToBList(shopGoodsList, HomeGoodsResult.class);
        List<String> goodsNos = result.stream().map(HomeGoodsResult::getGoodsNo).collect(Collectors.toList());
        if (ToolUtil.isEmpty(goodsNos)) {
            return BasePageFactory.createPageInfo(page);
        }
        //所有商品SKU集合
        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNos(goodsNos);
        for (HomeGoodsResult homeGoodsResult : result) {
            //主图处理
            String images = homeGoodsResult.getGoodsImgs();
            if (images.indexOf(",") != -1) {
                homeGoodsResult.setGoodsImgs(images.substring(0, images.indexOf(",")));
            }
            GoodsTypeResult goodsTypeResult = EnumGoodsType.getGoodsTypeByType(homeGoodsResult.getGoodsType());
            homeGoodsResult.setIsVipBuyGoods(goodsTypeResult.getIsVipBuyGoods());
            homeGoodsResult.setIsGoods(goodsTypeResult.getIsGoods());
            homeGoodsResult.setIsVipGoods(goodsTypeResult.getIsVipGoods());
            homeGoodsResult.setIsZoneGoods(goodsTypeResult.getIsZoneGoods());
            String goodsNo = homeGoodsResult.getGoodsNo();
            List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuList.stream().filter(x -> x.getGoodsNo().equals(goodsNo)).collect(Collectors.toList());
            //sku所有虚销售量
            Integer skuSaleVolume = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getSalesVolume).sum();
            //订单所有销售量
            Integer salesVolume = shopOrderService.countByGoodsNo(goodsNo);
            homeGoodsResult.setSaleCount(skuSaleVolume + salesVolume);
            //sku所有库存
            Integer allStock = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getStock).sum();
            homeGoodsResult.setAllStock(allStock);
            //查询单买价格
            ShopGoodsSku shopGoodsSkuLowPrice = shopGoodsSkus.stream().sorted(Comparator.comparing(ShopGoodsSku::getPrice)).collect(Collectors.toList()).get(0);
            homeGoodsResult.setPrice(shopGoodsSkuLowPrice.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            if (homeGoodsResult.getIsVipBuyGoods()) {
                homeGoodsResult.setReturnPoints(shopGoodsSkuLowPrice.getReturnPoints());
            }
            if (ToolUtil.isNotEmpty(shopGoodsSkuLowPrice.getSpecialPrice())) {
                homeGoodsResult.setSpecialPrice(shopGoodsSkuLowPrice.getSpecialPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            } else {
                homeGoodsResult.setSpecialPrice(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }
        page.setRecords(result);
        return BasePageFactory.createPageInfo(page);
    }

//    /**
//     * APP购物车展示商品
//     *
//     * @param params
//     * @return
//     */
//    public BaseResponse<List<AppGoodsResult>> getAppGoodsList(AppGoodsParam params) {
//        Page pageContext = BasePageFactory.defaultPage(params.getPage(), params.getLimit());
//        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ShopGoods::getStatus, true);
//        queryWrapper.and(x -> x.isNull(ShopGoods::getPublishTime).or().le(ShopGoods::getPublishTime, new Date()));
//        queryWrapper.eq(ShopGoods::getIsDeleted, false);
//        queryWrapper.orderByDesc(ShopGoods::getUpdateTime);
//        IPage page = this.page(pageContext, queryWrapper);
//        List<ShopGoods> shopGoodsList = page.getRecords();
//        List<AppGoodsResult> result = EntityConvertUtils.convertAListToBList(shopGoodsList, AppGoodsResult.class);
//        List<String> goodsNos = result.stream().map(AppGoodsResult::getGoodsNo).collect(Collectors.toList());
//        if (ToolUtil.isEmpty(goodsNos)) {
//            return BasePageFactory.createPageInfo(page);
//        }
//        //所有商品SKU集合
//        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNos(goodsNos);
//        for (AppGoodsResult goodsResult : result) {
//            //主图处理
//            String images = goodsResult.getGoodsImgs();
//            if (images.indexOf(",") != -1) {
//                goodsResult.setGoodsImgs(images.substring(0, images.indexOf(",")));
//            }
//            String goodsNo = goodsResult.getGoodsNo();
//            List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuList.stream().filter(x -> x.getGoodsNo().equals(goodsNo)).collect(Collectors.toList());
//            //查询单买价格
//            ShopGoodsSku shopGoodsSkuLowPrice = shopGoodsSkus.stream().sorted(Comparator.comparing(ShopGoodsSku::getPrice)).collect(Collectors.toList()).get(0);
//            goodsResult.setPrice(shopGoodsSkuLowPrice.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
//        }
//        page.setRecords(result);
//        return BasePageFactory.createPageInfo(page);
//    }

    public ShopGoods queryByGoodsNo(String goodsNo) {
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsNo, goodsNo);
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }

    public List<ShopGoods> listByGoodsNos(List<String> goodsNos) {
        if (ToolUtil.isEmpty(goodsNos)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ShopGoods::getGoodsNo, goodsNos);
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        return list(queryWrapper);
    }

    public List<ShopGoods> queryByCategoryNo(String categoryNo) {
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsCategoryNo, categoryNo);
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        return list(queryWrapper);
    }

    public BaseResponse<List<HomeGoodsResult>> goodsByLabelList(HomeGoodsByLabelParams params) {
        Page pageContext = BasePageFactory.defaultPage(params.getPage(), params.getLimit());
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsLabelNo, params.getLabelNo());
        queryWrapper.eq(ShopGoods::getStatus, true);
        if (params.getAccordingLabelShow()) {
            queryWrapper.eq(ShopGoods::getAccordingLabelShow, true);
        }
        queryWrapper.and(x -> x.eq(ShopGoods::getPublishType, 1).or().eq(ShopGoods::getPublishType, 2)
                .and(y -> y.isNull(ShopGoods::getPublishTime).or().le(ShopGoods::getPublishTime, new Date())));
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        queryWrapper.ne(ShopGoods::getGoodsType, -1);
        queryWrapper.orderByDesc(ShopGoods::getUpdateTime);
        IPage page = this.page(pageContext, queryWrapper);
        List<ShopGoods> shopGoodsList = page.getRecords();
        List<HomeGoodsResult> result = EntityConvertUtils.convertAListToBList(shopGoodsList, HomeGoodsResult.class);
        List<String> goodsNos = result.stream().map(HomeGoodsResult::getGoodsNo).collect(Collectors.toList());
        if (ToolUtil.isEmpty(goodsNos)) {
            return BasePageFactory.createPageInfo(page);
        }
        //所有商品SKU集合
        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNos(goodsNos);
        for (HomeGoodsResult homeGoodsResult : result) {
            //主图处理
            String images = homeGoodsResult.getGoodsImgs();
            if (images.indexOf(",") != -1) {
                homeGoodsResult.setGoodsImgs(images.substring(0, images.indexOf(",")));
            }
            GoodsTypeResult goodsTypeResult = EnumGoodsType.getGoodsTypeByType(homeGoodsResult.getGoodsType());
            homeGoodsResult.setIsVipBuyGoods(goodsTypeResult.getIsVipBuyGoods());
            homeGoodsResult.setIsGoods(goodsTypeResult.getIsGoods());
            homeGoodsResult.setIsVipGoods(goodsTypeResult.getIsVipGoods());
            homeGoodsResult.setIsZoneGoods(goodsTypeResult.getIsZoneGoods());
            String goodsNo = homeGoodsResult.getGoodsNo();
            List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuList.stream().filter(x -> x.getGoodsNo().equals(goodsNo)).collect(Collectors.toList());
            //sku所有虚销售量
//            Integer skuSaleVolume = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getSalesVolume).sum();
            //订单所有销售量
//            Integer salesVolume = shopOrderService.countByGoodsNo(goodsNo);
//            homeGoodsResult.setSaleCount(skuSaleVolume + salesVolume);
            //sku所有库存
//            Integer allStock = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getStock).sum();
//            homeGoodsResult.setAllStock(allStock);
            // 验证入口来源 查询单买价格
            ShopGoodsSku shopGoodsSkuLowPrice = shopGoodsSkus.stream().sorted(Comparator.comparing(ShopGoodsSku::getPrice)).collect(Collectors.toList()).get(0);
            homeGoodsResult.setPrice(shopGoodsSkuLowPrice.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            if (homeGoodsResult.getIsVipBuyGoods()) {
                homeGoodsResult.setReturnPoints(shopGoodsSkuLowPrice.getReturnPoints());
            }
            if (ToolUtil.isNotEmpty(shopGoodsSkuLowPrice.getSpecialPrice())) {
                homeGoodsResult.setSpecialPrice(shopGoodsSkuLowPrice.getSpecialPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            } else {
                homeGoodsResult.setSpecialPrice(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }
        page.setRecords(result);
        return BasePageFactory.createPageInfo(page);
    }

    public List<ShopGoods> queryByLabelNo(String labelNo) {
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsLabelNo, labelNo);
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        return list(queryWrapper);
    }

    public List<ShopGoods> listNoDeletedGoodsList() {
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        return list(queryWrapper);
    }

    public BaseResponse deleteGoods(Long id) {
        ShopGoods shopGoods = getById(id);
        shopGoods.setIsDeleted(true);
        saveOrUpdate(shopGoods);
        return BaseResponse.success("删除商品成功。");
    }

    public BaseResponse updateLabelShow(String goodsNo, Boolean isShow) {
        ShopGoods goods = this.queryByGoodsNo(goodsNo);
        if (ToolUtil.isEmpty(goods)) {
            return BaseResponse.error("商品不存在");
        }
        LambdaUpdateWrapper<ShopGoods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ShopGoods::getAccordingLabelShow, isShow);
        updateWrapper.eq(ShopGoods::getGoodsNo, goodsNo);
        this.update(updateWrapper);
        return BaseResponse.success();
    }

    public BaseResponse relatedLabel(String goodsNo, String goodsLabelNo) {
        ShopGoods goods = this.queryByGoodsNo(goodsNo);
        if (ToolUtil.isEmpty(goods)) {
            return BaseResponse.error("商品不存在");
        }
        LambdaUpdateWrapper<ShopGoods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ShopGoods::getGoodsLabelNo, goodsLabelNo);
        updateWrapper.eq(ShopGoods::getGoodsNo, goodsNo);
        this.update(updateWrapper);
        return BaseResponse.success();
    }

    public List<ShopGoods> listUnPublishGoods() {
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        queryWrapper.eq(ShopGoods::getStatus, false);
        queryWrapper.and(x -> x.isNotNull(ShopGoods::getPublishTime).le(ShopGoods::getPublishTime, new Date()));
        return list(queryWrapper);
    }

    /**
     * 0元购 及其 会员商品 专区
     *
     * @param type
     * @param pages
     * @param limit
     * @return
     */
    public BaseResponse<HomeGoodsResult> goodsItemList(String type, String pages, String limit) {
        Page pageContext = BasePageFactory.defaultPage(pages, limit);
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getStatus, true);
        if (type.equals("zero")) {
            queryWrapper.and(x -> x.eq(ShopGoods::getGoodsType, EnumGoodsType.ONE.getType())
                    .or().eq(ShopGoods::getGoodsType, EnumGoodsType.TWO.getType())
                    .or().eq(ShopGoods::getGoodsType, EnumGoodsType.FIVE.getType())
                    .or().eq(ShopGoods::getGoodsType, EnumGoodsType.SEVEN.getType()));
        } else if (type.equals("vip")) {
            queryWrapper.and(x -> x.eq(ShopGoods::getGoodsType, EnumGoodsType.ONE.getType())
                    .or().eq(ShopGoods::getGoodsType, EnumGoodsType.THREE.getType())
                    .or().eq(ShopGoods::getGoodsType, EnumGoodsType.FIVE.getType())
                    .or().eq(ShopGoods::getGoodsType, EnumGoodsType.SIX.getType()));
        }
        queryWrapper.and(x -> x.eq(ShopGoods::getPublishType, 1).or().eq(ShopGoods::getPublishType, 2)
                .and(y -> y.isNull(ShopGoods::getPublishTime).or().le(ShopGoods::getPublishTime, new Date())));
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        queryWrapper.ne(ShopGoods::getGoodsType, -1);
        queryWrapper.orderByDesc(ShopGoods::getUpdateTime);
        IPage page = this.page(pageContext, queryWrapper);
        List<ShopGoods> shopGoodsList = page.getRecords();
        List<HomeGoodsResult> result = EntityConvertUtils.convertAListToBList(shopGoodsList, HomeGoodsResult.class);
        List<String> goodsNos = result.stream().map(HomeGoodsResult::getGoodsNo).collect(Collectors.toList());
        if (ToolUtil.isEmpty(goodsNos)) {
            return BasePageFactory.createPageInfo(page);
        }
        //所有商品SKU集合
        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNos(goodsNos);
        for (HomeGoodsResult homeGoodsResult : result) {
            //主图处理
            String images = homeGoodsResult.getGoodsImgs();
            if (images.indexOf(",") != -1) {
                homeGoodsResult.setGoodsImgs(images.substring(0, images.indexOf(",")));
            }
            GoodsTypeResult goodsTypeResult = EnumGoodsType.getGoodsTypeByType(homeGoodsResult.getGoodsType());
            homeGoodsResult.setIsVipBuyGoods(goodsTypeResult.getIsVipBuyGoods());
            homeGoodsResult.setIsGoods(goodsTypeResult.getIsGoods());
            homeGoodsResult.setIsVipGoods(goodsTypeResult.getIsVipGoods());
            homeGoodsResult.setIsZoneGoods(goodsTypeResult.getIsZoneGoods());
            String goodsNo = homeGoodsResult.getGoodsNo();
            List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuList.stream().filter(x -> x.getGoodsNo().equals(goodsNo)).collect(Collectors.toList());
            //sku所有虚销售量
            Integer skuSaleVolume = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getSalesVolume).sum();
            //订单所有销售量
            Integer salesVolume = shopOrderService.countByGoodsNo(goodsNo);
            homeGoodsResult.setSaleCount(skuSaleVolume + salesVolume);
            //sku所有库存
            Integer allStock = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getStock).sum();
            homeGoodsResult.setAllStock(allStock);

            ShopGoodsSku shopGoodsSkuLowVipPrice = shopGoodsSkus.stream().sorted(Comparator.comparing(ShopGoodsSku::getVipPrice)).collect(Collectors.toList()).get(0);
            // 验证入口来源 返回对应价格
            if (type.equals("zero")) {
                homeGoodsResult.setPrice(shopGoodsSkuLowVipPrice.getPrice().toString());
                homeGoodsResult.setZeroPrice("0.00");
            } else if (type.equals("vip")) {
                homeGoodsResult.setPrice(shopGoodsSkuLowVipPrice.getPrice().toString());
                homeGoodsResult.setVipPrice(shopGoodsSkuLowVipPrice.getVipPrice().toString());
            }
            if (ToolUtil.isNotEmpty(shopGoodsSkuLowVipPrice.getSpecialPrice())) {
                homeGoodsResult.setSpecialPrice(shopGoodsSkuLowVipPrice.getSpecialPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            } else {
                homeGoodsResult.setSpecialPrice(new BigDecimal(0.00).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
        }
        page.setRecords(result);
        return BasePageFactory.createPageInfo(page);
    }

    public BaseResponse<List<HomeGoodsResult>> againGoodsByGoodsVipLevel(Integer goodsVipLevel, String pages, String limits) {
        Page pageContext = BasePageFactory.defaultPage(pages, limits);
        LambdaQueryWrapper<ShopGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoods::getGoodsType, EnumGoodsType.AGAIN.getType());
        queryWrapper.eq(ShopGoods::getAgainVipLevel, goodsVipLevel);
        queryWrapper.eq(ShopGoods::getStatus, true);
        queryWrapper.and(x -> x.eq(ShopGoods::getPublishType, 1).or().eq(ShopGoods::getPublishType, 2)
                .and(y -> y.isNull(ShopGoods::getPublishTime).or().le(ShopGoods::getPublishTime, new Date())));
        queryWrapper.eq(ShopGoods::getIsDeleted, false);
        queryWrapper.orderByDesc(ShopGoods::getUpdateTime);
        IPage page = this.page(pageContext, queryWrapper);
        List<ShopGoods> shopGoodsList = page.getRecords();
        List<HomeGoodsResult> result = EntityConvertUtils.convertAListToBList(shopGoodsList, HomeGoodsResult.class);
        List<String> goodsNos = result.stream().map(HomeGoodsResult::getGoodsNo).collect(Collectors.toList());
        if (ToolUtil.isEmpty(goodsNos)) {
            return BasePageFactory.createPageInfo(page);
        }
        //所有商品SKU集合
        List<ShopGoodsSku> shopGoodsSkuList = shopGoodsSkuService.listByGoodsNos(goodsNos);
        for (HomeGoodsResult homeGoodsResult : result) {
            //主图处理
            String images = homeGoodsResult.getGoodsImgs();
            if (images.indexOf(",") != -1) {
                homeGoodsResult.setGoodsImgs(images.substring(0, images.indexOf(",")));
            }
            String goodsNo = homeGoodsResult.getGoodsNo();
            List<ShopGoodsSku> shopGoodsSkus = shopGoodsSkuList.stream().filter(x -> x.getGoodsNo().equals(goodsNo)).collect(Collectors.toList());
            //sku所有虚销售量
            Integer skuSaleVolume = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getSalesVolume).sum();
            //订单所有销售量
            Integer salesVolume = shopOrderService.countByGoodsNo(goodsNo);
            homeGoodsResult.setSaleCount(skuSaleVolume + salesVolume);
            //sku所有库存
            Integer allStock = shopGoodsSkus.stream().mapToInt(ShopGoodsSku::getStock).sum();
            homeGoodsResult.setAllStock(allStock);
            // 验证入口来源 查询单买价格
            ShopGoodsSku shopGoodsSkuLowPrice = shopGoodsSkus.stream().sorted(Comparator.comparing(ShopGoodsSku::getAgainPrice)).collect(Collectors.toList()).get(0);
            homeGoodsResult.setAgainPrice(shopGoodsSkuLowPrice.getAgainPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            homeGoodsResult.setReturnPoints(shopGoodsSkuLowPrice.getReturnPoints());
        }
        page.setRecords(result);
        return BasePageFactory.createPageInfo(page);
    }
}
